package com.rainbow.chat.test.ws;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @Author: rainbow
 * @Description:
 */
public class WebSocketServerInit extends ChannelInitializer<SocketChannel> {
    private static String socketUri = "/chat";

    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServerInit.class);
    private SslContext sslContext;

    WebSocketServerInit(SslContext sslContext){
        this.sslContext = sslContext;
    }
    @Override
    protected void initChannel(SocketChannel channel) throws Exception {
        System.out.println("客户端连接：" + channel.remoteAddress());
        ChannelPipeline pipeline = channel.pipeline();
        if(sslContext!=null){
            pipeline.addLast(sslContext.newHandler(channel.alloc()));
        }
        pipeline.addLast("http-codec", new HttpServerCodec());
        // 用于大数据流的分区传输
        pipeline.addLast("http-chunked",new ChunkedWriteHandler());
        // 将多个消息转换为单一的 request 或者 response 对象，最终得到的是 FullHttpRequest 对象
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
        // 创建 WebSocket 之前会有唯一一次 Http 请求 (Header 中包含 Upgrade 并且值为 websocket)
        pipeline.addLast("http-request",new WebSocketHttpHandler());
        // 处理所有委托管理的 WebSocket 帧类型以及握手本身
//        pipeline.addLast("websocket-server", new WebSocketServerProtocolHandler(socketUri));
        // WebSocket RFC 定义了 6 种帧，TextWebSocketFrame 是我们唯一真正需要处理的帧类型
//        pipeline.addLast("text-frame",new WebSocketServerHandler())
        ;
    }
}
